package com.lxb.store.controller;

import com.lxb.store.entity.BuyGoods;
import com.lxb.store.entity.Goods;
import com.lxb.store.entity.ShopCar;
import com.lxb.store.entity.User;
import com.lxb.store.service.BuyGoodsService;
import com.lxb.store.service.GoodsService;
import com.lxb.store.service.ShopCarService;
import com.lxb.store.service.UserService;
import jdk.nashorn.internal.ir.IfNode;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;


import java.util.*;

@Controller
public class ShopCarController {

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private BuyGoodsService buyGoodsService;

    @Autowired
    private UserService userService;

    @Autowired
    private ShopCarService shopCarService;

    @GetMapping("/shopcar")
    public String shopCarIndex(@PageableDefault(size = 4,direction = Sort.Direction.DESC,sort = {"recommend"}) Pageable pageable,
                               Model model){
        //获取登录用户信息
        User loginUser = (User) SecurityUtils.getSubject().getPrincipal();
        //密码设置为空
        if(loginUser != null){
            loginUser.setPassword(null);
        }
        Page<BuyGoods> page = buyGoodsService.findAll(pageable, loginUser.getUsername());
        if (page == null){
            System.out.println("该用户没有购物车");
            model.addAttribute("user",loginUser);

            return "shopcar";
        }

        System.out.println("page="+page.getTotalElements());

        model.addAttribute("page",page);
        model.addAttribute("user",loginUser);
        return "shopcar";
    }


    /**
     * 加入购物车
     * @param id
     * @param num
     * @param color
     * @param price
     * @return
     */
    @PostMapping("/getshopcar")
    @ResponseBody
    public Map<String,String> ShopCar(@RequestParam("id") String id,
                       @RequestParam("num") String num,
                       @RequestParam("color") String color,
                       @RequestParam("price") String  price){
        //获取登录用户信息
        User loginUser = (User) SecurityUtils.getSubject().getPrincipal();

        Map<String,String> ret = new HashMap<>();
        if(loginUser == null){
            ret.put("status","no-login");
            ret.put("msg","请先登录！");
            return  ret;
        }


        if("".equals(id)){
            ret.put("status","error");
            ret.put("msg","商品id为空");
            return  ret;
        }
        if("".equals(num)){
            ret.put("status","error");
            ret.put("msg","商品数量为空");
            return  ret;
        }
        if("".equals(color)){
            ret.put("status","error");
            ret.put("msg","商品颜色为空");
            return  ret;
        }
        if("".equals(price)){
            ret.put("status","error");
            ret.put("msg","商品价格为空");
            return  ret;
        }
        System.out.println("id="+id+"num="+num+"color="+color+"price="+price);
        //数据库查询商品
        Goods goods = goodsService.getByID(Integer.parseInt(id));

        BuyGoods buyGoods = new BuyGoods();

        //名称
        buyGoods.setName(goods.getGoodsName());
        //价格
        buyGoods.setPrice(Float.parseFloat(price));
        //数量
        buyGoods.setNum(Integer.parseInt(num));
        //重量
        buyGoods.setWeight(goods.getGoodsWeight());
        //图片
        buyGoods.setImg(goods.getShowImg());
        //信息
        buyGoods.setInfo1(goods.getGoodsInfo1());
        buyGoods.setInfo2(goods.getGoodsInfo2());
        //推荐指数
        buyGoods.setRecommend(goods.getRecommend());
        //商品id
        buyGoods.setGoodsId(Integer.parseInt(id));
        //颜色
        buyGoods.setColor(color);

        //在数据库查找用户信息
        User user = userService.getByUsername(loginUser.getUsername());

        if(user == null){
            ret.put("status","error");
            ret.put("msg","该用户不存在");
            return  ret;
        }

        //判断是否购物车是否在该商品，有，则函数返回true并更新该商品在购物车的数量，否则返回false，执行新增
        if(buyGoodsService.checkBuyGoodsExist(user.getUsername(),goods.getId(),goods.getGoodsName(),Integer.parseInt(num),color)){
            ret.put("status","success");
            ret.put("msg","加入购物车成功!");
            return  ret;
        }

        //获取当前用户购物车
        ShopCar userShopCar = user.getShopCar();


        if(userShopCar == null){
             //用户没有购物车，新建
            userShopCar = new ShopCar();

            //在数据库新建购物车
            userShopCar = shopCarService.saveShopCar(userShopCar);
            if(userShopCar == null){
                ret.put("status","error");
                ret.put("msg","购物车新建失败！");
                return ret;
            }
            //在用户里保存购物车
            user.setShopCar(userShopCar);
            user = userService.update(user);
            if(user == null){
                ret.put("status","error");
                ret.put("msg","在用户里保存购物车失败！");
                return ret;
            }
        }

        //在商品中保存购物车
        buyGoods.setShopCar(userShopCar);

        //在数据库保存购买商品
        BuyGoods saveBuyGoods = buyGoodsService.save(buyGoods);
        if(saveBuyGoods == null){
            ret.put("status","error");
            ret.put("msg","加入购物车失败");
            return  ret;
        }

        //在购物车保存商品
        List<BuyGoods> list =userShopCar.getBuyGoodsList();
        list.add(saveBuyGoods);
        userShopCar.setBuyGoodsList(list);
        userShopCar =shopCarService.saveShopCar(userShopCar);
        if(userShopCar == null){
            ret.put("status","error");
            ret.put("msg","购物车里保存商品失败！");
            return  ret;
        }
        //在商品里保存购物车
        saveBuyGoods.setShopCar(userShopCar);
        saveBuyGoods =buyGoodsService.save(saveBuyGoods);
        if(saveBuyGoods == null){
            ret.put("status","error");
            ret.put("msg","在商品里保存购物车失败！");
            return  ret;
        }

        ret.put("status","success");
        ret.put("msg","加入购物车成功！");
        return ret;
    }

    /**
     * 删除购物车商品
     *
     */
    @GetMapping("/shopcar/delete")
    @ResponseBody
    public String  deleteGoods(@PageableDefault(size = 4,direction = Sort.Direction.DESC,sort = {"recommend"}) Pageable pageable,
                               Integer id,
                               Model model){

        //获取登录用户信息
        User loginUser = (User) SecurityUtils.getSubject().getPrincipal();
        //密码设置为空
        if(loginUser != null){
            loginUser.setPassword(null);
        }
        Page<BuyGoods> page = buyGoodsService.findAll(pageable, loginUser.getUsername());

        if(id == null){
            System.out.println("id为空");
        }
        buyGoodsService.delete(id);
        model.addAttribute("status","success");
        model.addAttribute("msg","删除商品成功");
        model.addAttribute("page",page);
        return "shopcar::goods_list";
    }


    /**
     * 在购物车增加一个商品数量
     * @param id
     * @param num
     * @return
     */
    @PostMapping("/shopcar/add")

    public String addGoodsNum(@PageableDefault(size = 4,direction = Sort.Direction.DESC,sort = {"recommend"}) Pageable pageable,
                              Integer id,
                              Integer num,
                              Model model){

        //获取登录用户信息
        User loginUser = (User) SecurityUtils.getSubject().getPrincipal();
        //密码设置为空
        if(loginUser != null){
            loginUser.setPassword(null);
        }
        Page<BuyGoods> page = buyGoodsService.findAll(pageable, loginUser.getUsername());
        if (page == null){
            System.out.println("该用户没有购物车");
            model.addAttribute("user",loginUser);
            return "redirect:shopcar";
        }
        if(id == null){

            model.addAttribute("msg","传入的商品id为空");
            model.addAttribute("page",page);
            return "shopcar::goods_list";
        }
        if(num < 1){

            model.addAttribute("msg","商品数量不能再改变");
            model.addAttribute("page",page);
            return "shopcar::goods_list";
        }

        int ok = shopCarService.addBuyGoodsNum(id);

        if(ok <1){

            model.addAttribute("msg","更新商品数量失败");
            model.addAttribute("page",page);
            return "shopcar::goods_list";

        }
        model.addAttribute("status","success");
        model.addAttribute("msg","增加商品数量成功");
        model.addAttribute("page",page);
        return "shopcar::goods_list";
    }

    /**
     * 在购物车减少一个商品数量
     * @param id
     * @param num
     * @return
     */
    @PostMapping("/shopcar/sub")
    public String subGoodsNum(@PageableDefault(size = 4,direction = Sort.Direction.DESC,sort = {"recommend"}) Pageable pageable,
                              Integer id,
                              Integer num,
                              Model model){

        //获取登录用户信息
        User loginUser = (User) SecurityUtils.getSubject().getPrincipal();
        //密码设置为空
        if(loginUser != null){
            loginUser.setPassword(null);
        }
        Page<BuyGoods> page = buyGoodsService.findAll(pageable, loginUser.getUsername());
        if (page == null){
            System.out.println("该用户没有购物车");
            model.addAttribute("user",loginUser);
            return "redirect:shopcar";
        }
        if(id == null){

            model.addAttribute("msg","传入的商品id为空");
            model.addAttribute("page",page);
            return "shopcar::goods_list";
        }
        if(num <=1){

            model.addAttribute("msg","商品数量不能再改变");
            model.addAttribute("page",page);
            return "shopcar::goods_list";
        }

        int ok = shopCarService.subBuyGoodsNum(id);

        if(ok <1){
            model.addAttribute("msg","更新商品数量失败");
            model.addAttribute("page",page);
            return "shopcar::goods_list";

        }
        model.addAttribute("status","success");
        model.addAttribute("msg","减少商品数量成功");
        model.addAttribute("page",page);
        return "shopcar::goods_list";
    }

    @PostMapping("/shopcar/deleteNum")
    @ResponseBody
    public Map<String,String> deleteNum(Integer[] ids){

        Map<String,String> ret = new HashMap<>();
        if(ids.length == 0){
            ret.put("msg","请选择一项数据");
            ret.put("status","error");
            return  ret;
        }
        //数组转化为List
        List<Integer> idsList = new ArrayList<>(Arrays.asList(ids));
        buyGoodsService.deleteNum(idsList);
        ret.put("msg","批量删除成功");
        ret.put("status","success");
        return ret;
    }

}
